const { User, Caregiver, Pet } = require('../models');
const { AppError } = require('../middleware/errorHandler');
const logger = require('../utils/logger');
const { validationResult } = require('express-validator');
const { Op } = require('sequelize');

// 过滤对象，只保留允许的字段
const filterObj = (obj, ...allowedFields) => {
  const newObj = {};
  Object.keys(obj).forEach(el => {
    if (allowedFields.includes(el)) newObj[el] = obj[el];
  });
  return newObj;
};

// 获取用户公开信息（无需登录）
exports.getUserPublicInfo = async (req, res, next) => {
  try {
    const user = await User.findOne({
      where: { 
        id: req.params.id,
        active: true 
      },
      attributes: ['id', 'firstName', 'lastName', 'avatar', 'stats', 'createdAt', 'preferences']
    });
    
    if (!user) {
      return next(new AppError('用户不存在', 404));
    }
    
    // 构建公开信息对象
    const stats = user.stats || {};
    const preferences = user.preferences || {};
    const publicInfo = {
      id: user.id,
      firstName: user.firstName,
      lastName: user.lastName,
      fullName: user.fullName,
      avatar: user.avatar,
      rating: stats.rating || { average: 0, count: 0 },
      memberSince: user.createdAt,
      language: preferences.language || 'zh-CN'
    };
    
    // 如果用户已登录，可以提供更多信息
    if (req.user) {
      publicInfo.isLoggedIn = true;
    }
    
    res.status(200).json({
      status: 'success',
      data: {
        user: publicInfo
      }
    });
  } catch (error) {
    logger.error('获取用户公开信息错误:', error);
    return next(new AppError('获取用户信息失败', 500));
  }
};

// 获取所有用户（管理员功能）
exports.getAllUsers = async (req, res, next) => {
  try {
    // 构建查询条件
    const where = {};
    
    // 角色过滤
    if (req.query.role) {
      where.role = req.query.role;
    }
    
    // 激活状态过滤
    if (req.query.active !== undefined) {
      where.active = req.query.active === 'true';
    }
    
    // 邮箱验证状态
    if (req.query.emailVerified !== undefined) {
      where.emailVerified = req.query.emailVerified === 'true';
    }
    
    // 搜索关键词
    if (req.query.search) {
      where[Op.or] = [
        { username: { [Op.like]: `%${req.query.search}%` } },
        { email: { [Op.like]: `%${req.query.search}%` } },
        { firstName: { [Op.like]: `%${req.query.search}%` } },
        { lastName: { [Op.like]: `%${req.query.search}%` } }
      ];
    }
    
    // 分页
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    // 排序
    const order = [];
    if (req.query.sort) {
      const sortFields = req.query.sort.split(',');
      sortFields.forEach(field => {
        if (field.startsWith('-')) {
          order.push([field.substring(1), 'DESC']);
        } else {
          order.push([field, 'ASC']);
        }
      });
    } else {
      order.push(['createdAt', 'DESC']);
    }
    
    // 执行查询
    const { count, rows: users } = await User.findAndCountAll({
      where,
      order,
      limit,
      offset,
      attributes: { exclude: ['password'] }
    });
    
    res.status(200).json({
      status: 'success',
      results: users.length,
      total: count,
      page,
      totalPages: Math.ceil(count / limit),
      data: {
        users
      }
    });
  } catch (error) {
    logger.error('获取用户列表错误:', error);
    return next(new AppError('获取用户列表失败', 500));
  }
};

// 获取单个用户
exports.getUser = async (req, res, next) => {
  try {
    const user = await User.findByPk(req.params.id, {
      attributes: { exclude: ['password'] }
    });
    
    if (!user) {
      return next(new AppError('未找到该用户', 404));
    }
    
    res.status(200).json({
      status: 'success',
      data: {
        user
      }
    });
  } catch (error) {
    logger.error('获取用户信息错误:', error);
    return next(new AppError('获取用户信息失败', 500));
  }
};

// 更新当前用户信息
exports.updateMe = async (req, res, next) => {
  try {
    // 检查验证错误
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }
    
    // 1) 如果用户试图更新密码，返回错误
    if (req.body.password || req.body.passwordConfirm) {
      return next(
        new AppError('此路由不用于密码更新，请使用 /update-password', 400)
      );
    }
    
    // 2) 过滤不允许更新的字段
    const filteredBody = filterObj(
      req.body,
      'firstName',
      'lastName',
      'phone',
      'dateOfBirth',
      'gender',
      'avatar',
      'address',
      'preferences'
    );
    
    // 3) 更新用户文档
    const user = await User.findByPk(req.user.id);
    await user.update(filteredBody);
    
    logger.info(`用户更新信息: ${user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: '用户信息更新成功',
      data: {
        user
      }
    });
  } catch (error) {
    logger.error('更新用户信息错误:', error);
    return next(new AppError('更新用户信息失败', 500));
  }
};

// 删除当前用户（软删除）
exports.deleteMe = async (req, res, next) => {
  try {
    const user = await User.findByPk(req.user.id);
    await user.update({ active: false });
    
    logger.info(`用户删除账户: ${req.user.email}`);
    
    res.status(204).json({
      status: 'success',
      message: '账户已删除',
      data: null
    });
  } catch (error) {
    logger.error('删除用户账户错误:', error);
    return next(new AppError('删除账户失败', 500));
  }
};

// 管理员创建用户
exports.createUser = async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }
    
    const newUser = await User.create(req.body);
    
    logger.info(`管理员创建用户: ${newUser.email}`);
    
    res.status(201).json({
      status: 'success',
      message: '用户创建成功',
      data: {
        user: newUser
      }
    });
  } catch (error) {
    logger.error('创建用户错误:', error);
    return next(new AppError('创建用户失败', 500));
  }
};

// 管理员更新用户
exports.updateUser = async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }
    
    // 不允许通过此路由更新密码
    if (req.body.password) {
      return next(new AppError('此路由不用于密码更新', 400));
    }
    
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      return next(new AppError('未找到该用户', 404));
    }
    
    await user.update(req.body);
    
    logger.info(`管理员更新用户: ${user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: '用户信息更新成功',
      data: {
        user
      }
    });
  } catch (error) {
    logger.error('更新用户错误:', error);
    return next(new AppError('更新用户失败', 500));
  }
};

// 管理员删除用户
exports.deleteUser = async (req, res, next) => {
  try {
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      return next(new AppError('未找到该用户', 404));
    }
    
    await user.destroy();
    
    logger.info(`管理员删除用户: ${user.email}`);
    
    res.status(204).json({
      status: 'success',
      message: '用户删除成功',
      data: null
    });
  } catch (error) {
    logger.error('删除用户错误:', error);
    return next(new AppError('删除用户失败', 500));
  }
};

// 管理员激活/禁用用户
exports.toggleUserStatus = async (req, res, next) => {
  try {
    const user = await User.findByPk(req.params.id);
    
    if (!user) {
      return next(new AppError('未找到该用户', 404));
    }
    
    await user.update({ active: !user.active });
    
    const action = user.active ? '激活' : '禁用';
    logger.info(`管理员${action}用户: ${user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: `用户已${action}`,
      data: {
        user
      }
    });
  } catch (error) {
    logger.error('切换用户状态错误:', error);
    return next(new AppError('操作失败', 500));
  }
};

// 获取用户统计信息
exports.getUserStats = async (req, res, next) => {
  try {
    const { sequelize } = require('../config/database');
    
    // 总体统计
    const totalUsers = await User.count();
    const activeUsers = await User.count({ where: { active: true } });
    const verifiedUsers = await User.count({ where: { emailVerified: true } });
    
    // 角色分布
    const roleStats = await User.findAll({
      attributes: [
        'role',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['role']
    });
    
    // 最近注册用户
    const recentUsers = await User.findAll({
      order: [['createdAt', 'DESC']],
      limit: 5,
      attributes: ['id', 'firstName', 'lastName', 'email', 'createdAt', 'role']
    });
    
    res.status(200).json({
      status: 'success',
      data: {
        overview: {
          totalUsers,
          activeUsers,
          verifiedUsers,
          inactiveUsers: totalUsers - activeUsers,
          unverifiedUsers: totalUsers - verifiedUsers
        },
        roleDistribution: roleStats,
        recentUsers
      }
    });
  } catch (error) {
    logger.error('获取用户统计错误:', error);
    return next(new AppError('获取统计信息失败', 500));
  }
};

// 搜索用户
exports.searchUsers = async (req, res, next) => {
  try {
    const { q, role, active, verified } = req.query;
    
    if (!q || q.length < 2) {
      return next(new AppError('搜索关键词至少需要2个字符', 400));
    }
    
    // 构建搜索条件
    const where = {};
    
    where[Op.or] = [
      { firstName: { [Op.like]: `%${q}%` } },
      { lastName: { [Op.like]: `%${q}%` } },
      { username: { [Op.like]: `%${q}%` } },
      { email: { [Op.like]: `%${q}%` } },
      { phone: { [Op.like]: `%${q}%` } }
    ];
    
    // 添加过滤条件
    if (role) where.role = role;
    if (active !== undefined) where.active = active === 'true';
    if (verified !== undefined) where.emailVerified = verified === 'true';
    
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    const { count, rows: users } = await User.findAndCountAll({
      where,
      attributes: { exclude: ['password'] },
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });
    
    res.status(200).json({
      status: 'success',
      results: users.length,
      total: count,
      page,
      totalPages: Math.ceil(count / limit),
      data: {
        users
      }
    });
  } catch (error) {
    logger.error('搜索用户错误:', error);
    return next(new AppError('搜索用户失败', 500));
  }
};

// 上传用户头像
exports.uploadAvatar = async (req, res, next) => {
  try {
    if (!req.file) {
      return next(new AppError('请选择要上传的图片', 400));
    }
    
    // TODO: 实现文件上传逻辑（如上传到云存储）
    const avatarUrl = `/uploads/avatars/${req.file.filename}`;
    
    const user = await User.findByPk(req.user.id);
    await user.update({ avatar: avatarUrl });
    
    logger.info(`用户上传头像: ${user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: '头像上传成功',
      data: {
        user
      }
    });
  } catch (error) {
    logger.error('上传头像错误:', error);
    return next(new AppError('上传头像失败', 500));
  }
};

// 获取用户活动日志
exports.getUserActivity = async (req, res, next) => {
  try {
    const user = await User.findByPk(req.params.id, {
      attributes: ['id', 'lastActive', 'createdAt', 'updatedAt']
    });
    
    if (!user) {
      return next(new AppError('未找到该用户', 404));
    }
    
    // TODO: 实现详细的活动日志功能
    // 这里可以从其他集合中获取用户的活动记录
    
    res.status(200).json({
      status: 'success',
      data: {
        userId: user.id,
        lastActive: user.lastActive,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt,
        activities: [] // 待实现
      }
    });
  } catch (error) {
    logger.error('获取用户活动错误:', error);
    return next(new AppError('获取用户活动失败', 500));
  }
};